#include "mainwindow.h"
#include "appsettings.h"

#include <QtCore/qdatetime.h>
#include <QtCore/qdebug.h>
#include <QtCore/qfile.h>
#include <QtCore/qmutex.h>
#include <QtCore/qtextcodec.h>
#include <QtCore/qtextstream.h>
#include <QtCore/qtranslator.h>
#include <QtGui/qapplication.h>

static QFile s_log("qeda_log.txt");
static QMutex s_mutex;

void myMessageOutput(QtMsgType type, const char *msg)
{
    s_mutex.lock();
    s_log.open(QFile::Append | QFile::Text);
    QTextStream strm(&s_log);
    QTime now = QTime::currentTime();
    strm << now.toString("HH:mm:ss.zzz ") << QString::fromUtf8(msg) << endl;
    s_log.close();
    s_mutex.unlock();
}

int main(int argc, char *argv[])
{
    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    Q_INIT_RESOURCE(core);

    if (g_appSettings->asBool("DebugLog", false))
    {
        s_log.open(QFile::WriteOnly);
        char bom[] = { 0xEF, 0xBB, 0xBF };
        s_log.write(bom, sizeof(bom));
        s_log.close();
        qInstallMsgHandler(myMessageOutput);
        qDebug() << "-- Debug Started --";
    }

    QApplication a(argc, argv);

    QTranslator translator;
    QString suffix = g_appSettings->asString("View/Language", "en");
    if (suffix != "en")
    {
        translator.load("core_" + suffix, ":/translations");
        a.installTranslator(&translator);
    }

    MainWindow w;
    w.show();
    
    return a.exec();
}
